﻿using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using SJKP.PDFConversion.Client;
using SJKP.PDFConversion.Extensions;

namespace SJKP.PDFConversion.OCRProcessorWebpart
{
    public partial class OCRProcessorWebpartUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnProcessFile_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;
            if (fuPdfFile.HasFile == false || fuPdfFile.FileBytes.Length == 0)
            {
                Page.Validators.Add(new CustomValidator() {ErrorMessage = "File has no content",IsValid = false});
                return;
            }

            byte[] converted = new OCRClientHelper(SPServiceContext.Current).ProcessPdf(fuPdfFile.FileBytes);

            SPWeb web = SPContext.Current.Site.RootWeb;
            SPDocumentLibrary list = null;
            try 
            {   
                list = web.GetList(txtListUrl.Text) as SPDocumentLibrary;
            } 
            catch(FileNotFoundException fnfe)
            {
                Page.Validators.Add(new CustomValidator() { ErrorMessage = String.Format("List with url '{0}' not found",txtListUrl.Text), IsValid = false });
                return;
            }

            list.UploadFile(converted, fuPdfFile.FileName);           
        }

        
    }
}
